package br.com.mmm.javacenter.framework.view.taglib.tags;

import java.io.IOException;

import javax.servlet.jsp.JspException;

import br.com.mmm.javacenter.framework.annotations.AttributeTagSupport;
import br.com.mmm.javacenter.framework.annotations.GenericTagSupport;
import br.com.mmm.javacenter.framework.entity.EntidadeBase;
import br.com.mmm.javacenter.framework.reflection.FieldAdapter;
import br.com.mmm.javacenter.framework.reflection.ReflectionFacade;
import br.com.mmm.javacenter.framework.view.taglib.helper.Render;
import br.com.mmm.javacenter.framework.view.taglib.helper.RenderFactory;


public class InputGenericTag extends InputTag{
	private FieldAdapter field;
	private EntidadeBase<?> entidade;

	public void doTag() throws JspException, IOException {
		Render render = RenderFactory.getRender(field.getField().getType());
		render.setContext(getJspContext());
		render.setFragment(getJspBody());
		ReflectionFacade rf = new ReflectionFacade(render);
		ReflectionFacade rfEntidade = new ReflectionFacade(entidade);
		rf.set("name", field.getName());
		rf.set("value", rfEntidade.get(field.getName()));
		rf.set("maxLength", field.getLength());
		if(field.getField().isAnnotationPresent(GenericTagSupport.class)){
			GenericTagSupport annotation = field.getField().getAnnotation(GenericTagSupport.class);
			AttributeTagSupport[] attributes = annotation.value();
			for(AttributeTagSupport attributeTagSupport:attributes){
				rf.inject(attributeTagSupport.name(),attributeTagSupport.value());
			}
		}
		if(rf.get("label") == null){
			rf.set("label", field.getName());
		}
		rf.set("klass",field.getField().getType());
		render.make();
		
	}

	public FieldAdapter getField() {
		return field;
	}

	public void setField(FieldAdapter field) {
		this.field = field;
	}

	public EntidadeBase<?> getEntidade() {
		return entidade;
	}

	public void setEntidade(EntidadeBase<?> entidade) {
		this.entidade = entidade;
	}
}
